package com.javabank.ws.dao.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.javabank.ws.dao.AccountDAO;
import com.javabank.ws.domain.Account;
import com.javabank.ws.domain.Account_;

public class AccountDAOImpl extends BaseDAOImpl<Account> implements AccountDAO {
	public AccountDAOImpl() {
    }

	/**
	 * JPA-tutorial: http://www.ibm.com/developerworks/java/library/j-typesafejpa/
	 */
	@Override
	public Account getByRekening(Integer rekeningnummer) {
		open();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Account> query = cb.createQuery(Account.class);
        Root<Account> a = query.from(Account.class);
        Predicate condition = cb.equal(a.get(Account_.rekeningnummer), rekeningnummer);
        
        query.where(condition);
        
        TypedQuery<Account> typedQuery = em.createQuery(query);
        List<Account> result = typedQuery.getResultList();
        
        if(result.size() == 1){
        	// Rekeningnummer has unique index. If size is 1, then found, else not found
        	return result.get(0);
        }else{
        	return null;
        }
	}

	@Override
	public Account newAccount(Account account) {
		
		return account;
	}
}
